import React from 'react'
import PropTypes from 'prop-types'
import { Form, Modal, Tree } from 'antd'
import { CreateMenuTree } from 'utils'
import { basicDictTypeData } from 'utils/seletLocalData'

const TreeNode = Tree.TreeNode
const permissionModal = ({
  item,
  currentPermission,
  onOk,
  updateSelectKey,
  menuTreeData,
  selectKey,
  ...modalProps
}) => {
  const handleOk = () => {
    const result = [...selectKey]
    selectKey.forEach((current) => {
      menuTreeData.forEach((currentMenu) => {
        if (currentMenu.id == current && currentMenu.bpid !== 0) {
          result.push(currentMenu.bpid.toString())
        }
      })
    })
    const set = new Set(result)
    const array = Array.from(set)
    onOk(array)
  }
  const modalOpts = {
    ...modalProps,
    onOk: handleOk,
  }
  const onCheck = (checkedKeys) => {
    updateSelectKey(checkedKeys)
  }
  const permissionData = currentPermission.map((permission) => {
    if (permission.id) {
      return permission.id.toString()
    }
  })
  const renderTreeNodes = (data) => {
    return data.map((current) => {
      if (current.children) {
        return (
          <TreeNode title={current.title} key={current.key} dataRef={current}>
            {renderTreeNodes(current.children)}
          </TreeNode>
        )
      }
      return <TreeNode {...current} />
    })
  }
  return (
    <Modal {...modalOpts}>
      <Tree
        checkable
        onCheck={onCheck}
        defaultCheckedKeys={permissionData}
        //checkStrictly
      >
        {
          renderTreeNodes(CreateMenuTree(menuTreeData))
        }
      </Tree>
    </Modal>
  )
}

permissionModal.propTypes = {
  form: PropTypes.object.isRequired,
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
  menuTreeData: PropTypes.array,
  selectKey: PropTypes.array,
}

export default Form.create()(permissionModal)
